<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>闭包中this的指向</title>
</head>

<body>

  <script>

    // ()()再自执行的函数的前面如果有JS代码，必须用";"来表示语句结束。

    /*
     (function () {
       var name = "肖申克";
       function getName() {
         console.log('闭包中的this', this);
         return name;
       }
 
       function setName(v) {
         name = v;
       }
 
       window.my = { getUserName: getName, setUserName: setName }
     })()

     my.getUserName(); //{getUserName: ƒ, setUserName: ƒ} 
     */
    /*
    (function () {
      var name = "肖申克";
      function getName() {
        console.log('闭包中的this', this);
        return name;
      }

      function setName(v) {
        name = v;
      }

      window.getUserName = getName;
      window.setUserName = setName;
    })()
    getUserName(); // window.getUserName();  方法里面的this指向window
 */

    /*  // function fn1() {
     //   console.log("fn1", this); // window
     //   return function fn2() {
     //     console.log("fn2", this); // window
     //     return function fn3(this) {
     //       console.log("fn3", this);  // window
     //       return () => {
     //         console.log("fn4", this);// window
     //       }
     //     }
     //   }
     // }
 
     // fn1()()()(); */

    function fn1() {
      console.log("fn1", this); // window
      return function fn2() {
        console.log("fn2", this); // window

        return function fn3(_this) { // 参数 this
          console.log("fn3 的 _this", _this);  // Person {name: '姚磊', say: ƒ}
          console.log("fn2.   . this", this);// window

          return () => {
            console.log("fn4", this);// window
          }
        }
      }
    }
    function Person(name) {
      this.name = name
      this.say = function () {
        // console.log("say:", this); //say: Person {name: '姚磊', say: ƒ}

        fn1()()(this)();

      }
    }

    new Person('姚磊').say()

  </script>
</body>

</html>